from datetime import datetime
from loguru import logger
import sys
import os


class AppLogger:
    """
    日志类
    """

    @staticmethod
    def generate_formatter(color: str = None) -> str:
        """
        生成日志格式
         :param color: 颜色
        :return: 格式字符串
         """
        return ("{time:YYYY-MM-DD HH:mm:ss.SSS} | " +
                f"<{color}>" + "{level}" + f"</{color}> | " +
                f"<{color}>" + "{file}:[{line}]" + f"</{color}> >> " +
                f"<{color}>" + "{message}" + f"</{color}>"
                if color is not None else
                "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level} | {file}:[{line}] >> {message}")

    def __init__(self, log_name: str):
        # 设置输出格式
        logger.remove(0)
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter(color="light-blue"),
                   filter=lambda record: record["level"].name == "DEBUG")
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter("light-green"),
                   filter=lambda record: record["level"].name == "INFO")
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter("light-yellow"),
                   filter=lambda record: record["level"].name == "WARNING")
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter("light-red"),
                   filter=lambda record: record["level"].name == "ERROR")
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter("light-magenta"),
                   filter=lambda record: record["level"].name == "CRITICAL")
        logger.add(sys.stdout, colorize=True, format=self.generate_formatter("light-cyan"),
                   filter=lambda record: record["level"].name == "SUCCESS")

        # 追加日志文件
        if not os.path.exists('./log'):
            os.makedirs('./log')
        # 获取当前时间
        now = datetime.now()

        # 初始化上一次创建日志文件的日期
        last_log_date = now

        # 构造当前月份的日志文件名
        log_file_path = os.path.join("log", f"{log_name}_{now.year}-{now.month:02d}.log")

        # 检查是否需要创建新的日志文件
        if not os.path.exists(log_file_path):
            try:
                # 如果文件不存在，则创建新的日志文件
                logger.add(log_file_path, format=self.generate_formatter())
                # 更新上一次创建日志文件的日期
                last_log_date = now
            except Exception as e:
                print(f"Error creating log file: {e}")
        else:
            # 如果文件已存在，则直接使用
            logger.add(log_file_path, format=self.generate_formatter())

        # 提示初始化完成
        logger.info(f"=====App Logger初始化完成, 执行项目{log_name}=====")
